<?php

/* Startup stuff, load setup.php which sets up Henry Class as $Henry */
session_start();
require_once "setup.php"; //sets up a new Henry

if(isset($_GET['logout']))
	if($_GET['logout']) $Henry->logout();

/* Functions */
function load($what){
	global $Henry; $theme=$Henry->getSetting('theme');
		if($what=='profile') include 'themes/'.$theme.'/profile.php'; 
		if($what=='login-register') include 'themes/'.$theme.'/login-register.php'; 
		if($what=='page') include 'themes/'.$theme.'/page.php'; 
}

function loadThemePart($part){ 
	global $Henry; $theme=trim($Henry->getSetting('theme'));
		include "themes/".$theme."/$part";
}

loadThemePart('language.php');

/* Ol' Henry */
class Henry{ 
	public function siteTitle($tricks=''){
		$this->o($this->getSetting('sitetitle'),$tricks);
	}

	public function themeUrl($tricks=null){
		$this->o($this->getSetting('siteurl')."themes/".$this->getSetting('theme'),$tricks);
	}

	public function isLoginRegister(){ //34-65 is misbehaving (not even throwing error)
		if(inUrl('login-register.php'))
			return true; 
				else return false;
	}

	public function isProfile(){
		if(inUrl('profile.php')) 
			return true; 
				else return false;
	}

	private function inUrl($match){
		if(stristr($_SERVER['SCRIPT_FILENAME'],$match)) return true;
			else return false;
	}

	public function bodyClasses($tricks=null,$tags=' '){
		if($this->isLoginRegister()){
			$tags.='login-register ';
		}else{
			$tags.='not-login-register ';
		}

		if($this->isProfile()){
			$tags.='profile ';
		}else{
			$tags.='not-profile ';
		}

		//$this->o(trim($tags),$tricks);
	}

	public function out($o,$whats=''){$this->o($o,$whats);} //alias of o();
	public function o($o,$whats=''){ //basic output that knows tricks!
		if(stristr($whats,'language')){
			if(stristr($whats,'echooff')){
				if(stristr($whats,'htmloff')){
					return $this->language($o);
				}else{
					return htmlentities($this->language($o));
				}
			}else{
				if(stristr($whats,'htmloff')){
					echo $this->language($o);
				}else{
					echo htmlentities($this->language($o));
				}
			}
		}else{
			if(stristr($whats,'echooff')){
				if(stristr($whats,'htmloff')){
					return $o;
				}else{
					return htmlentities($o);
				}
			}else{
				if(stristr($whats,'htmloff')){
					echo $o;
				}else{
					echo htmlentities($o);
				}
			}
			
		}
	}

	public function logout(){
		session_destroy();
			if(!$this->messageThrown('loginfailed')) //if the login didn't fail just because of bad pass/email
				$this->message('logout'); //only show the message if there wasn't an attempted login already
		$this->go('login');
	}

	public function go($where){
		if($where=='login') $this->h('login-register.php');
		if($where=='profile') $this->h('profile.php');
		if($where=='home') $this->h('index.php');
		if($where=='page') $this->h('page.php');
	}

	private function h($where){
		header("location: $where");
	}

	public function installDb($sql){
		$this->db($sql);
	}

	/* db */
	private function db($sql){

		//echo $sql;
	
		$con = mysql_connect(
			$this->getSetting('dbserver'),
			$this->getSetting('dbuser'),
			$this->getSetting('dbpassword')
		);

		mysql_select_db($this->getSetting('database'), $con);
		
		if(!$con) die($this->language('notconnect') . mysql_error());

		$result = mysql_query($sql, $con);

		$data=false;

    	if(!$result)
    		echo $this->language('errorcomdb').mysql_error();
    			else{
    				if($result!==true && $result!==false){
    					while($row = mysql_fetch_assoc($result)){
    						$data[]=$row;
    					}

    					return $data;
    				}
    			}
    				
		mysql_close($con);
	}

	/* Settings */
	private $setting;

	/* Constructor */
	function __construct($settingsArray){
		if(is_array($settingsArray)){
				$this->setSetting('dbserver',	$settingsArray['dbserver']);
				$this->setSetting('dbuser',		$settingsArray['dbuser']);
				$this->setSetting('dbpassword',	$settingsArray['dbpassword']);
				$this->setSetting('database',	$settingsArray['database']);
				$this->setSetting('language',	$settingsArray['language']);
				$this->setSetting('siteurl',	$settingsArray['siteurl']);
				$this->setSetting('salt',		$settingsArray['salt']);
				$this->setSetting('theme',		$settingsArray['theme']);
				$this->setSetting('sitetitle',	$settingsArray['sitetitle']);
		}else{
			return false;
		}
	}

	public function getSetting($setting){
		return $this->setting[$setting];
	}

	public function setSetting($setting,$value){
		$this->setting[$setting]=$value;
	}

	public function siteUrl(){
		return rtrim($this->getSetting('siteurl'),"/");
	}

	/* login */
	public function isloggedin(){
		//if email is not set in session, not logged in
		if(isset($_SESSION['email']))
			if(!$_SESSION['email'])
				{
					return false;
				}
					else{
						if($this->checkUser($_SESSION['email'],$_SESSION['pass'])){
							return true;
						} else{
							return false;
						}
					}
		}

	private function checkUser($email,$password){

		//print_r($_SESSION);
		
		$user=$this->db("
			SELECT * 
			FROM  `users` 
			WHERE `email` = '$email';
		");

		//print_r($user[0]);

		
			if($password == $user[0]['pass']){
				if($user[0]['active']=='1'){
					return true;
				}else {
					$this->message('youraccountnotactive');
						return false;
				}
			}else{
				return false;
			}
		

	}

	private function storeLoginInSession($email,$password){
		$_SESSION['email']=strtolower($email);
		$_SESSION['pass']=($password);
			$this->go('home');
	}

	public function language($key,$echo=false){
			if(isset($this->languages[$this->getSetting('language')][$key])) 
				if(!$echo) return $this->languages[$this->getSetting('language')][$key];
					else echo $this->languages[$this->getSetting('language')][$key];
	}

	public function register(){
		if($this->isLoggedIn()) $this->go('home');

		if(isset($_POST['action'])){
			if($_POST['action']=='register'){
				if($_POST['password1'] == $_POST['password2']){
					if(!$this->userExists($_POST['email'])){
						$this->dbInsert('users',
							array(
								'NULL',
								strtolower($_POST['email']), 
								$this->md5s($_POST['password1']),
								array(
									'fname'=>$_POST['fname'],
									'lname'=>$_POST['lname']
								)
							)
						);
						$this->message('thanksregister');
						$this->mailActivation($_POST['email']);
					}else{
						$this->message('alreadyregistered');
					}

				}else{
					$this->message('passwordnotmatch');
				}
			}
		}
	}

	private function mailActivation($email){
		$subject = $email.$this->language('mailactivationsubject'); 
		$message=$this->language('mailactivationmessage');
		$message.="\n\n";

		$message.=$this->getSetting('siteurl')."login-register.php?action=confirmregistration&email=".$email."&key=".$this->userStoredPassword($email);

		$headers = 'From: noreply@' . $_SERVER['SERVER_NAME'] . "\r\n" .
    		'Reply-To: noreply@' . $_SERVER['SERVER_NAME'] . "\r\n" .
    		'X-Mailer: PHP/' . phpversion();

		mail($email, $subject, $message, $headers);
	}

	private $mode; //localprofile,remoteprofile,page

	private function mode(){
		return $this->mode;
	}

	private function setMode($mode){
		if(
			$mode=='local'
			|| $mode=='remote'
			|| $mode=='page'
		){
			$this->mode=$mode;
		}else{
			//what should I do here?
		}
	}

	public function registerHome(){
		if(!$this->isLoggedIn())
			$this->go('login');
				else $this->go('profile');
	}

	public function registerProfile(){
		if(!$this->isLoggedIn())
				$this->go('login');
					$this->localProfileData=$this->db("SELECT data from users where email = '".$_SESSION['email']."';");
						if($this->_g('id')){
							$this->remoteProfileData=$this->db("SELECT data from users where id = '".$this->_g('id')."';");
								$this->setMode('remote');
						}else{
							$this->setMode('local');
						}
	}

	private $localProfileData;
	private $remoteProfileData;

	public function profileData($key=NULL,$localRemote='local'){
		$localRemote=strtolower($localRemote);

		if($localRemote=='local' || $localRemote=='l') 
			$data=unserialize($this->localProfileData[0]['data']);
		if($localRemote=='remote' | $localRemote=='r') 
			$data=unserialize($this->remoteProfileData[0]['data']);

		if($key && $key!='dump'){
			if(isset($data[$key]))
				return $data[$key];
					else return false;
		}elseif($key=='dump'){
			return $data;
		}else{
			return false;
		}
	}

	public function profile($term,$localRemote='local'){
		$term=strtolower($term);

			if(strstr($term,'name')){
				if(strstr($term,'first')){ 
					return $this->profileData('fname',$localRemote);
				}elseif(strstr($term,'last')){
					return $this->profileData('lname',$localRemote);
				}elseif(strstr($term,'full')){
					return $this->profileData('fname',$localRemote) . " " . $this->profileData('lname',$localRemote);
				}else{
					return $this->profileData($term,$localRemote);
				}
			}
	}

	public function registerPage(){
		if(!$this->isLoggedIn())
				$this->go('login');
					else{ 
						if(!$this->_g('id')){
							$this->message('404page');
						}
						$this->setMode('page');
					}
	}

	public function activation(){ //this is ran when a link is clicked in email sent via mailActivation()
		if($this->_g('action')=='confirmregistration'){
			//values passed through query st.
			$email=$this->_g('email');
			$key=$this->_g('key');
			
			//compare key with what is stored in db (to ensure match)
			$compareKey = $this->userStoredPassword($email);
			
			//Now, compare and change the database
			if($key == $compareKey){
				//they keys matched (which only could be used through proper email)
				//let's modify the "active" column in the db
				$this->db("UPDATE `users` SET  `active` =  '1' WHERE  `users`.`email` = '".$email."';");
				$this->message('acchasactive');
			}else{
				
			}

		}
	}

	public function _p($key){ //a better function for getting $_POST
		if(isset($_POST[$key]))
			return $_POST[$key];
				else return false;
	}

	public function _g($key){ //a better function for getting $_GET
		if(isset($_GET[$key]))
			return $_GET[$key];
				else return false;
	}

	public function registerRegister(){
		$this->login();
		$this->register();
		$this->resetPassword();
		$this->activation();
		
		if($this->isLoggedIn()) 
			$this->go('profile');
	}

	public function login(){
		if($this->isLoggedIn()) $this->go('home');

		if(isset($_POST['action'])){
			if($_POST['action']=='login'){
				
				if($this->checkUser($_POST['email'],$this->md5s($_POST['password']))){
					$this->storeLoginInSession($_POST['email'],
						$this->md5s($_POST['password']));
				}else{
					if(!$this->messageThrown('youraccountnotactive')) //if this message wasn't already thrown
						$this->message('loginfailed');	//send this message

						$this->logout(); //kill the session
				}

			}		
		}
	}



	private function resetPasswordMail($email){

		$subject = $email.$this->language('passresreq');
		$message= $this->language('requestpasswordchangemail');
		$message.=
			$this->siteUrl()
			."/login-register.php?action=reset&email="
				.$email
			."&key=".$this->userStoredPassword($email)
		;

		$headers = 'From: noreply@' . $_SERVER['SERVER_NAME'] . "\r\n" .
    		'Reply-To: noreply@' . $_SERVER['SERVER_NAME'] . "\r\n" .
    		'X-Mailer: PHP/' . phpversion();

		mail($email, $subject, $message, $headers);
		//echo $message;
	}

	public function generatePassword($length=9, $strength=0) {
		$vowels = 'aeuy';
		$consonants = 'bdghjmnpqrstvz';
		if ($strength & 1) {
			$consonants .= 'BDGHJLMNPQRSTVWXZ';
		}
		if ($strength & 2) {
			$vowels .= "AEUY";
		}
		if ($strength & 4) {
			$consonants .= '23456789';
		}
		if ($strength & 8) {
			$consonants .= '@#$%';
		}
 	 
		$password = '';
		$alt = time() % 2;
		for ($i = 0; $i < $length; $i++) {
			if ($alt == 1) {
				$password .= $consonants[(rand() % strlen($consonants))];
				$alt = 0;
			} else {
				$password .= $vowels[(rand() % strlen($vowels))];
				$alt = 1;
			}
		}
		return $password;
	}


	private function sendPasswordToMail($email,$newPassword){

		$subject = $email.$this->language('mailpassressucc');
		$message=$this->language('mailpasswasresetto').$newPassword;
		$message.="\n\n";

		$headers = 'From: noreply@' . $_SERVER['SERVER_NAME'] . "\r\n" .
    		'Reply-To: noreply@' . $_SERVER['SERVER_NAME'] . "\r\n" .
    		'X-Mailer: PHP/' . phpversion();

		mail($email, $subject, $message, $headers);


	}

	private function userStoredPassword($email){
		$data = $this->db("SELECT pass from users where email = '".$email."';");
			return $data[0]['pass'];
	}

	public function resetPassword(){
		if($this->isLoggedIn()) $this->go('home');
		if(isset($_POST['action'])){
			if($_POST['action']=='resetpassword'){
				if($this->userExists($_POST['email'])){
					//do reset, send email to click link that resets.
						$this->resetPasswordMail($_POST['email']);
							$this->message('passwordresetsent');
				}else{
					$this->message('usernoexist');
				}
			}
		}elseif(isset($_GET['action'])){
			if($_GET['action']=='reset'){
				$newPassword=$this->generatePassword();
					$this->db("
						UPDATE `users` SET  `pass` =  '".$this->md5s($newPassword)."' WHERE  `users`.`email` ='".$_GET['email']."';
					");
						if($this){
							$this->message('hasbeenreset');
							$this->sendPasswordToMail($_GET['email'],$newPassword);
						}
			}
		}
	}




	public function md5s($what){
		return md5(
			strrev(md5($this->salt())) //reverse the salt and put it before the password
				.$what.
			md5($this->salt()) //put md5(d) normal salt after the password
		);
	}

	public function salt(){
		return $this->getSetting('salt');
	}

	private function userExists($email){

		$user=$this->db("
			SELECT email 
			FROM  `users` 
			WHERE `email` = '$email';
		");
		
		if(strtolower($user[0]['email'])==strtolower($email))
			return true;
				else return false;

	}

	/* Created to help make serializing diverse, just in case
	it doesn't work, we can tweak it to work the best */
	public function serialize($data){
		return serialize($data);
	}

	private function dbInsert($table,$valuesArray){
		if($table=='users'){
			$sql="
			
				INSERT INTO  `users` (
					`id` ,
					`email` ,
					`pass` ,
					`data`,
					`time` ,
					`pagecreator` ,
					`active`
					
				)
				VALUES (
					NULL ,  '$valuesArray[1]',  
					'$valuesArray[2]',  
					'".$this->serialize($valuesArray[3])."',
					NULL,
					'',
					''

				);
			
			";
			$this->db($sql);
		}

	}

	private $_messages;

	private function message($languageKey='custom',$custom=null){
		if($custom==null){
			$this->_messages[$languageKey]=$this->language($languageKey);
		}else{
			$this->_messages[$languageKey]=$custom;
		}
	}

	public function loginFailed(){
		if($this->messageThrown('loginfailed')) return true;
			else return false;
	}

	public function messageThrown($key){
		if(is_array($this->_messages)){
			$flippedArray = array_flip($this->_messages);
			foreach($flippedArray as $messageKey){
				if(strtolower($messageKey) == strtolower($key)) return true;
					else return false;
			}
			//print_r($flippedArray);
		}
	}

	public function messages($before='<p>',$after='</p>'){
		if(is_array($this->_messages)){
			foreach($this->_messages as $message){
				echo $before;
					echo $message;
				echo $after;
			}
		}
	}

	public function headActions(){
		?><!--Custom head stuff Henry needs --><?php
	}

	public function header(){
		loadThemePart('header.php');
	}

	public function footer(){
		loadThemePart('footer.php');
	}

	

	public function footerActions(){
		?><!--Custom footer stuff Henry needs --><?php
	}

	public $languages;
	


}

?>
